package persistence;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

public class DAO<T> {
	private EntityManager em;
	private Class<T> clazz;

	public DAO(EntityManager em, Class<T> clazz) {
		this.em = em;
		this.clazz = clazz;
	}

	public void salva(T t) {
		this.em.getTransaction().begin();
		this.em.persist(t);
		this.em.getTransaction().commit();
	}

	public void atualiza(T t) {
		this.em.getTransaction().begin();
		this.em.merge(t);
		this.em.getTransaction().commit();
	}

	public T remove(T t) {
		this.em.getTransaction().begin();
		this.em.remove(t);
		this.em.getTransaction().commit();
		return t;
	}

	public T recupera(Long id) {
		return this.em.find(clazz, id);
	}

	public List<T> lista() {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<T> cq = cb.createQuery(clazz);
		Root<T> root = cq.from(clazz);
		cq.select(root);
		return em.createQuery(cq).getResultList();
	}
}